// app.js
import mqtt from './utils/mqtt.js';
const aliyunOpt = require('./utils/aliyun/aliyun_connect.js');

App({
  globalData: {
    mqttClient: null,
    mqttStatus: 'disconnected', // disconnected, connecting, connected
    reconnectCounts: 0,
    mqttHost: '', // 存储host用于重连
    maxReconnectAttempts: 5, // 最大重连尝试次数
    mqttOptions: {
      protocolVersion: 4,
      clean: false,
      reconnectPeriod: 5000,
      connectTimeout: 30 * 5000,
      resubscribe: true,
      clientId: 'WeChat',
      password: '',
      username: '',
    },
    aliyunInfo: {
      productKey: 'a1jBWZqwUM3',
      deviceName: 'WeChat',
      deviceSecret: '7cc201b787444aa539b4b6197d4ccde2',
      regionId: 'cn-shanghai',
      pubTopic: '/a1jBWZqwUM3/WeChat/user/WeChat',
      subTopic: '/a1jBWZqwUM3/WeChat/user/get',
    },
    temperature: 25,  
    humidity: 50,
    heaterStatus: false,
    status:'',
    id:'',

    isAdminLoggedIn: false,
    userRoles: {
      admin: "管理员",
      user: "用户",
      pass: "骑手"
    },
    currentUser: null,
    passedPassword: null
  },

  onLaunch() {
    this.initMQTTConnection();
  },

  initMQTTConnection() {
    const clientOpt = aliyunOpt.getAliyunIotMqttClient({
      productKey: this.globalData.aliyunInfo.productKey,
      deviceName: this.globalData.aliyunInfo.deviceName,
      deviceSecret: this.globalData.aliyunInfo.deviceSecret,
      regionId: this.globalData.aliyunInfo.regionId,
    });

    const host = 'wxs://' + clientOpt.host;
    this.globalData.mqttOptions.clientId = clientOpt.clientId;
    this.globalData.mqttOptions.password = clientOpt.password;
    this.globalData.mqttOptions.username = clientOpt.username;

    this.connectToMqtt(host);

    this.globalData.mqttClient.on('connect', () => {
      this._startHeartbeat(); // 连接成功后启动心跳
    });
  },

  // 心跳包（每20秒发送一次空消息）
  _startHeartbeat() {
    if (this._heartbeatTimer) clearInterval(this._heartbeatTimer);
    this._heartbeatTimer = setInterval(() => {
      if (this.globalData.mqttStatus === 'connected') {
        this.globalData.mqttClient.publish(
          this.globalData.aliyunInfo.pubTopic,
          JSON.stringify({ type: 'heartbeat' }) // 发送空消息或特定协议
        );
      }
    }, 20000); // 20秒间隔
  },
  _scheduleReconnect() {
    if (this._reconnectTimer) clearTimeout(this._reconnectTimer);
    this._reconnectTimer = setTimeout(() => {
      if (this.globalData.mqttStatus !== 'connected') {
        console.log('尝试重新连接...');
        this.connectToMqtt(this.globalData.mqttHost);
      }
    }, 5000); // 5秒后重试
  },
  // 监听断开事件
  setupMQTTListeners() {
    this.globalData.mqttClient.on('close', () => {
      this.globalData.mqttStatus = 'disconnected';
      this._scheduleReconnect(); // 断开后触发重连
    });
  },


  connectToMqtt(host) {
    this.globalData.mqttStatus = 'connecting';
    
    if (this.globalData.mqttClient) {
      this.globalData.mqttClient.end();
    }

    this.globalData.mqttClient = mqtt.connect(host, this.globalData.mqttOptions);

    this.globalData.mqttClient.on('connect', (connack) => {
      const msg = this.globalData.reconnectCounts === 0 ? '首次连接成功' : '重新连接成功';
      this.globalData.mqttStatus = 'connected';
      this.globalData.reconnectCounts += 1;
      
      wx.showToast({ title: msg, icon: 'success' });
      
      this.globalData.mqttClient.subscribe(this.globalData.aliyunInfo.subTopic, (err) => {
        if (!err) console.log('订阅成功');
      });
    });

    this.globalData.mqttClient.on("message", (topic, payload) => {
      try {
        const dataFromALY = JSON.parse(payload);
        this.globalData.temperature = dataFromALY.temp;
        this.globalData.humidity = dataFromALY.humi;
        this.globalData.status = dataFromALY.status;
        this.globalData.id = dataFromALY.id;
            // 新增密码有效性验证逻辑
    if (dataFromALY.password) {
      const newPassword = dataFromALY.password;
      const isValidPassword = Array.isArray(newPassword) &&      // 检查密码是否符合要求：4位且每个字符不为空
        newPassword.length === 4 &&
        newPassword.every(c => String(c).trim() !== '');
      if (isValidPassword) {      // 只有有效密码才更新全局数据
        this.globalData.password = newPassword;
      } else {
        this.globalData.password = ['', '', '', ''];
      }
    }         // 通知所有页面更新数据
          this.notifyPages('updateData', {
          temperature: dataFromALY.temp,
          humidity: dataFromALY.humi,
          password:this.globalData.password,
          status:dataFromALY.status,
          id:dataFromALY.id,
        });
        console.log(this.globalData.id);
        console.log(this.globalData.status);
        console.log(this.globalData.password);
        console.log(this.globalData.temperature);
        console.log(this.globalData.humidity);
      }
       catch (error) {
        console.log('消息解析错误:', error);
      }
    });

    this.globalData.mqttClient.on("error", (error) => {
      console.log("连接错误:", error);
      this.globalData.mqttStatus = 'disconnected';
      wx.showToast({ title: '连接异常', icon: 'none' });
    });

    this.globalData.mqttClient.on("offline", () => {
      this.globalData.mqttStatus = 'disconnected';
      wx.showToast({ title: '连接断开', icon: 'none' });
    });
  },

  sendCommand(data) {
    if (this.globalData.mqttClient && this.globalData.mqttStatus === 'connected') {
      this.globalData.mqttClient.publish(this.globalData.aliyunInfo.pubTopic, JSON.stringify(data));
      console.log('已发送指令:', data);
      return true;
    } else {
      wx.showToast({ title: '服务器未连接', icon: 'none' });
      return false;
    }
  },

  // 页面注册和通知机制
  pages: [],
  
  registerPage(page) {
    this.pages.push(page);
  },
  
  unregisterPage(page) {
    const index = this.pages.indexOf(page);
    if (index !== -1) {
      this.pages.splice(index, 1);
    }
  },
  
  notifyPages(event, data) {
    this.pages.forEach(page => {
      if (page[event] && typeof page[event] === 'function') {
        page[event](data);
      }
    });
  },

    // 生命周期管理
    onShow() {
      if (this.globalData.mqttStatus === 'disconnected') {
        this.connectToMqtt();
      }
    },
  
    onHide() {
      this._clearHeartbeat();
      if (this._reconnectTimer) clearTimeout(this._reconnectTimer);
    },

     // 历史记录相关
    getCurrentState() {
      let state = wx.getStorageSync('currentState');
      if (!state) {
        state = this.initDefaultState();
      }
      return state;
    },
  
    initUserRole(role) {
      this.globalData.currentUser = role;
    },
  
    initDefaultState() {
      const defaultState = {
        id:1,
        isDoorOpened: false,
        isHeated: false,
        newPassword: "0000",
        lastUpdate: Date.now()
      };
      wx.setStorageSync('currentState', defaultState);
      return defaultState;
    },
   
    updateDeviceState(partial) {
      const current = this.getCurrentState();
      const newState = {
        ...current,
        ...partial,
        lastUpdate: Date.now()
      };
    
      // 仅当密码变更时才检查有效性（移除非密码操作拦截）
      if (partial.newPassword) {
        if (partial.newPassword === '0000' || !partial.newPassword.every(c => String(c).trim() !== '')) {
          return; // 无效密码不更新
        }
      }
    
      const now = new Date();
      const pad = n => n.toString().padStart(2, '0');
      const formattedTime = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
    
      const historyEntry = {
        user: this.globalData.currentUser,
        formattedTime: formattedTime,
        ...partial
      };
    
      wx.setStorageSync('currentState', newState);
      
      const history = wx.getStorageSync('history') || [];
      wx.setStorageSync('history', [historyEntry, ...history].slice(0, 100));
    },
    
    clearHistory() {
      wx.removeStorageSync('history');
    }

});